﻿// RankingSejmowy 1.0 - Polish parliment statistics for the masses.
// Copyright (C) 2010 Jarosław Dubrownik
//  
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//  
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//  
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Transform;
using RankingSejmowy.Model;

namespace RankingSejmowy.DAL.DeputiesVotes
{
    public class DeputyVotesRepository : Repository<DeputyVote>, IDeputyVotesRepository
    {
        #region IDeputyVotesRepository Members

        public int GetAbsentCount(int cadence, ISession session)
        {
            var criteria = GetRowCountCriteriaThruVotings(cadence, session);
            criteria.Add(Restrictions.Eq("Vote", EVote.None));
            return (int) criteria.UniqueResult();
        }

        public int GetAllCount(int cadence, ISession session)
        {
            var criteria = GetRowCountCriteriaThruVotings(cadence, session);
            return (int) criteria.UniqueResult();
        }

        public int GetPartyAllCount(int cadence, string partyName, ISession session)
        {
            var criteria = GetRowCountCriteriaThruDeputies(cadence, partyName, session);
            return (int) criteria.UniqueResult();
        }

        public VoteCount[] GetVoteCount(int cadence, string partyName, ISession session)
        {
            var detachedCriteria = CreateVoteCriteria(partyName, cadence, session);
            var voteCriteria = session.CreateCriteria<DeputyVote>()
                // SELECT dv.VotingId, dv.Vote, COUNT(dv.Vote) Count
                .SetProjection(Projections.ProjectionList()
                                   .Add(Projections.Count("Vote"), "Count")
                                   .Add(Projections.GroupProperty("Voting.Id"), "VotingId"))
                //WHERE dv.DeputyVoteId IN (...)
                .Add(Subqueries.PropertyIn("Id", detachedCriteria))
                .SetResultTransformer(Transformers.AliasToBean(typeof (VoteCount)));

            return voteCriteria.List<VoteCount>().ToArray();
        }

        public SpecificVoteCount[] GetSpecificVoteCount(int cadence, string partyName, ISession session)
        {
            var detachedCriteria = CreateVoteCriteria(partyName, cadence, session);
            var specVoteCriteria = session.CreateCriteria<DeputyVote>()
                .SetProjection(Projections.ProjectionList()
                                   .Add(Projections.Count("Vote"), "Count")
                                   .Add(Projections.GroupProperty("Vote"), "Vote")
                                   .Add(Projections.GroupProperty("Voting.Id"), "VotingId"))
                .Add(Subqueries.PropertyIn("Id", detachedCriteria))
                .SetResultTransformer(Transformers.AliasToBean(typeof (SpecificVoteCount)));

            return specVoteCriteria.List<SpecificVoteCount>().ToArray();
        }

        public int GetPartyAbsentCount(int cadence, string partyName, ISession session)
        {
            var criteria = GetRowCountCriteriaThruDeputies(cadence, partyName, session);
            criteria.Add(Restrictions.Eq("Vote", EVote.None));
            return (int) criteria.UniqueResult();
        }

        #endregion

        private DetachedCriteria CreateVoteCriteria(string partyName, int cadence, ISession session)
        {
            return DetachedCriteria.For<DeputyVote>()
                // JOIN Deputy d ON d.Id = DeputyVoteId
                .CreateAlias("Deputy", "d")
                // JOIN DeputiesToPartyCadences dtpc ON d.DeputyId = dtpc.DeputyId
                .CreateAlias("d.PartyCadences", "pc")
                // JOIN PartyCadence pc ON pc.PartyCadenceId = dtpc.PartyCadenceId
                // JOIN Cadence c ON pc.CadenceId = c.CadenceId
                .CreateAlias("pc.Cadence", "c")
                // JOIN Party p ON p.PartyId = pc.PartyId
                .CreateAlias("pc.Party", "p")
                // WHERE c.CadenceNum = 1 AND p.Name = 'party1'
                .Add(Restrictions.Eq("p.Name", partyName) && Restrictions.Eq("c.CadenceNum", cadence))
                // SELECT DeputyVoteId ...
                .SetProjection(Projections.Id());
        }

        private ICriteria GetRowCountCriteriaThruVotings(int cadence, ISession session)
        {
            return CreateCriteria(session)
                // JOIN Voting v ON dv.VotingId = v.VotingId
                .CreateAlias("Voting", "v")
                // JOIN Meeting m ON v.MeetingId = m.MeetingId
                .CreateAlias("v.Meeting", "m")
                //JOIN Cadence c ON m.CadenceId = c.CadenceId
                .CreateAlias("m.Cadence", "c")
                // WHERE c.CadenceNum = 1
                .Add(Restrictions.Eq("c.CadenceNum", cadence))
                // SELECT COUNT(*)
                .SetProjection(Projections.RowCount());
        }

        private ICriteria GetRowCountCriteriaThruDeputies(int cadence, string partyName, ISession session)
        {
            return CreateCriteria(session)
                // JOIN Deputy d ON dv.DeputyId = d.DeputyId
                .CreateAlias("Deputy", "d")
                // JOIN DeputiesToPartyCadences dtpc ON d.DeputyId = dtpc.DeputyId
                .CreateAlias("d.PartyCadences", "pc")
                // JOIN PartyCadence pc ON pc.PartyCadenceId = dtpc.PartyCadenceId
                // JOIN Cadence c ON pc.CadenceId = c.CadenceId
                .CreateAlias("pc.Cadence", "c")
                // JOIN Party p ON p.PartyId = pc.PartyId
                .CreateAlias("pc.Party", "p")
                // WHERE c.CadenceNum = 1 AND p.Name = 'party1'
                .Add(Restrictions.Eq("c.CadenceNum", cadence))
                .Add(Restrictions.Like("p.Name", partyName))
                // SELECT COUNT(*)
                .SetProjection(Projections.RowCount());
        }
    }
}